package com.luhuiguo.cms.client.presenter;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.luhuiguo.cms.client.GlobalConstants;
import com.luhuiguo.cms.client.GlobalMessages;
import com.luhuiguo.cms.shared.event.LoginEvent;
import com.luhuiguo.cms.shared.rpc.GetCurrentUser;
import com.luhuiguo.cms.shared.rpc.GetCurrentUserResult;
import com.luhuiguo.gwt.dispatcher.client.DispatcherAsync;
import com.luhuiguo.gwt.presenter.client.EventBus;
import com.luhuiguo.gwt.presenter.client.widget.WidgetContainerDisplay;
import com.luhuiguo.gwt.presenter.client.widget.WidgetContainerPresenter;

public class AppPresenter extends WidgetContainerPresenter<AppPresenter.Display> {

    public interface Display extends WidgetContainerDisplay {

    }

    private DispatcherAsync dispatcher;

    private GlobalConstants constants;

    @SuppressWarnings("unused")
    private GlobalMessages messages;

    @SuppressWarnings("unused")
    private HeaderPresenter headerPresenter;

    @SuppressWarnings("unused")
    private NavigationPresenter navigationPresenter;

    @SuppressWarnings("unused")
    private MainPresenter mainPresenter;

    @Inject
    public AppPresenter(Display display, EventBus eventBus, DispatcherAsync dispatcher, GlobalConstants constants,
            GlobalMessages messages, HeaderPresenter headerPresenter, NavigationPresenter navigationPresenter,
            MainPresenter mainPresenter) {

        super(display, eventBus, headerPresenter, navigationPresenter, mainPresenter);

        this.dispatcher = dispatcher;
        this.constants = constants;
        this.messages = messages;

        this.headerPresenter = headerPresenter;
        this.navigationPresenter = navigationPresenter;
        this.mainPresenter = mainPresenter;

    }

    @Override
    protected void onBind() {
        super.onBind();

        checkUser();
    }

    private void checkUser() {
        dispatcher.execute(new GetCurrentUser(), new AsyncCallback<GetCurrentUserResult>() {
            public void onFailure(Throwable caught) {
                redirect(constants.loginUrl());
            }

            public void onSuccess(GetCurrentUserResult result) {
                eventBus.fireEvent(new LoginEvent(result.get()));
            }
        });
    }

    public static native void redirect(String url)/*-{
        $wnd.location = url;
    }-*/;

}
